package com.example.myapplication;

import static android.app.PendingIntent.getActivity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.myapplication.model.SendMailTask;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class BasicActivity extends AppCompatActivity {
    EditText editText, editText1, editText2, editText3, editText4, editText5, editText6;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic);

        editText = findViewById(R.id.editText);
        editText1 = findViewById(R.id.editText1);
        editText2 = findViewById(R.id.editText2);
        editText3 = findViewById(R.id.editText3);
        editText4 = findViewById(R.id.editText4);
        editText5 = findViewById(R.id.editText5);
        editText6 = findViewById(R.id.editText6);

        SharedPreferences sharedPreferences = getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
        String username = sharedPreferences.getString("user", "Default");
        String url = "http://39.107.92.86:5000/queryprofile?phone_number=" + username;
        new ProfileTask().execute(url);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = editText.getText().toString();
                String string1 = editText1.getText().toString();
                String string2 = editText2.getText().toString();
                String string3 = editText3.getText().toString();
                String string4 = editText4.getText().toString();
                String string5 = editText5.getText().toString();
                String string6 = editText6.getText().toString();
                String sql = "http://39.107.92.86:5000/modify_account?phone_number=" + username +
                        "&name=" + string + "&birthdata=" + string1+ "&height=" + string2 + "&weight="
                        + string3 + "&bloodpressure=" + string4 + "&historical=" + string5 + "&allergy=" + string6;
                new UpdateProfileTask().execute(sql);
            }
        });

        ImageView imageView_arrow = findViewById(R.id.imageView_arrow);
        imageView_arrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private class UpdateProfileTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String urlString = params[0];
            String result = "";

            try {
                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                reader.close();
                result = sb.toString();

                urlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                result = "Error: " + e.getMessage();
            }

            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                boolean success = jsonObject.optBoolean("success");

                if (success) {
                    Toast.makeText(BasicActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(BasicActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(BasicActivity.this, "解析错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class ProfileTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String urlString = params[0];
            String result = "";

            try {
                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                reader.close();
                result = sb.toString();

                urlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                result = "Error: " + e.getMessage();
            }

            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String name = jsonObject.optString("name");
                String birthdata = jsonObject.optString("birthdata");
                String height = jsonObject.optString("height");
                String weight = jsonObject.optString("weight");
                String bloodpressure = jsonObject.optString("bloodpressure");
                String historical = jsonObject.optString("historical");
                String allergy = jsonObject.optString("allergy");

                if (!name.isEmpty() && !name.equals("null")) {
                    editText.setText(name);
                }
                if (!birthdata.isEmpty() && !birthdata.equals("null")) {
                    editText1.setText(birthdata);
                }
                if (!height.isEmpty() && !height.equals("null")) {
                    editText2.setText(height);
                }
                if (!weight.isEmpty() && !weight.equals("null")) {
                    editText3.setText(weight);
                }
                if (!bloodpressure.isEmpty() && !bloodpressure.equals("null")) {
                    editText4.setText(bloodpressure);
                }
                if (!historical.isEmpty() && !historical.equals("null")) {
                    editText5.setText(historical);
                }
                if (!allergy.isEmpty() && !allergy.equals("null")) {
                    editText6.setText(allergy);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(BasicActivity.this, "Error parsing JSON", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
